import React, {useEffect, useState} from 'react';
import {useAppDispatch} from "@/hooks";
import {
    delBatchRemoveAsync,
    delHospitalSetByIdAsync,
    getHospitalSetAsync,
    getHospitalSetLockIdAsync,
    useSelectorHosp
} from "@/store/slice/hosp";
import {Button, Switch, Tooltip, Table, Space, Popconfirm, message, Form, Input} from "antd";
import {FormOutlined, DeleteOutlined} from "@ant-design/icons"
import {useSelectCommon} from "@/store/slice/common";
import HospitalModal from "@/pages/hospital/hospitalSet/components/HospitalModal";
import {delHospitalSetById} from "@/api/hosp";
import {changeQuery} from "@/store/slice/hosp";

function HospitalSet() {
    const dispatch = useAppDispatch();
    const {hospSetList} = useSelectorHosp();
    const {pageInfo,loading} = useSelectCommon();
    //自定义删除loading，因为点击其他的分页或搜索时，都会触发到common中的loading
    const [delLoading, setDelLoading] = useState<boolean>(false)
    const [form] = Form.useForm();//创建form表单的实例对象
    //控制Modal窗口打开或关闭
    const [isModalVisible, setIsModalVisible] =useState<boolean>(false);
    // 控制modal的标题
    const [modalTitle,setModalTitle] = useState<string>("添加医院设置");
    // 指定修改的内容
    const [hospitalSetInfo,setHospitalSetInfo] = useState<any>(null);
    //通过id是否一致来关闭确认删除框
    const [selectedId, setSelectedId] = useState<number>(-1);
    //选中要删除的位置
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
    useEffect(() => {
        dispatch(getHospitalSetAsync(1,5))
        return () => { //即将卸载阶段
            form.setFieldsValue({});//将表单内容置空
            dispatch(changeQuery({})); //把query参数的对象，置空
        }
    }, [])
    return (
        <div>
            <Space style={{marginBottom: 16}} >
                <Button type="primary" onClick={() => {
                    setHospitalSetInfo({}) //设置为空对象，则需二次判断
                    // setHospitalSetInfo(null) //可以实现，并且不用第二次判断，但是会报警告
                    setModalTitle('添加医院设置')
                    setIsModalVisible(true)
                }}>添加医院设置</Button>
                <Button type="primary" onClick={
                    async () => {
                        setDelLoading(true);
                        await dispatch(delBatchRemoveAsync(selectedRowKeys));
                        setSelectedRowKeys([]);
                        setDelLoading(false);
                        message.success('批量删除'+selectedRowKeys.length+'成功');
                    }
                } disabled={selectedRowKeys.length === 0} loading={delLoading}>
                    批量删除
                </Button>
                {/*<span style={{marginLeft: 8}}>*/}
                {/*  {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}*/}
                {/*</span>*/}
                <Form
                    form={form}
                    name="basic"
                    initialValues={{ remember: true }}
                    layout={'inline'}//让表单横向排列
                    onFinish={(values) => {
                        // console.log(values)
                        // dispatch(getHospitalSetAsync(1, 5, values))
                        dispatch(changeQuery(values));//优化搜索 不用再传值
                        dispatch(getHospitalSetAsync(1, 5));
                    }}
                    autoComplete="off"
                >
                    <Form.Item
                        name="hosname"
                    >
                        <Input placeholder={'请输入医院名称'}/>
                    </Form.Item>

                    <Form.Item
                        name="hoscode"
                    >
                        <Input placeholder={'请输入医院编码'}/>
                    </Form.Item>

                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                           提交
                        </Button>
                    </Form.Item>
                    <Form.Item >
                        <Button onClick={() => {
                            form.resetFields();//清空表单
                        }} htmlType="button">
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Space>
            <Table
                rowSelection = {{
                    selectedRowKeys,
                    onChange(newSelectedRowKeys: React.Key[]){
                        // console.log(newSelectedRowKeys)
                        setSelectedRowKeys(newSelectedRowKeys);//当改变了selectedRowKeys的状态时，newSelectedRowKeys的数组才会增加值，才能被选中
                    }
                }}
                loading={loading}
                pagination={{ //{/*pagination分页器，设为 false 时不展示和进行分页*/}
                    ...pageInfo,
                    // current: 2,
                    // pageSize: 7,
                    // total: 20,
                    onChange(page,pageSize){
                        console.log(page,pageSize, form.getFieldsValue());
                        // dispatch(getHospitalSetAsync(page,pageSize, form.getFieldsValue())); //获取列表，传递当前页数，和每页显示数
                        //优化搜索，及分页 改变params的状态 ，不用再给获取医院设置传值
                        dispatch(changeQuery(form.getFieldsValue()));
                        dispatch(getHospitalSetAsync(page,pageSize))
                    }
                }}
                // rowSelection={rowSelection}
                rowKey={"id"}
                /*增加表格边框*/
                bordered={true}
                scroll={{x:1800}}
                columns={[
                    {
                        title:"序号",
                        width:70,
                        align:"center",// 居中
                        // dataIndex:"id",
                        // 第一个参数：如果没有设置dataIdex,那么值为该行信息
                        render(value,rows,index){
                            const {current, pageSize} = pageInfo;
                            return pageSize*(current-1) + index+1;
                        }
                    },{
                        title:"医院名称",
                        align:"center",
                        width:200,
                        ellipsis:true,// 超过宽度将自动省略
                        dataIndex:"hosname"
                    },{
                        title:"医院编号",
                        align:"center",
                        dataIndex:"hoscode"
                    },{
                        title:"是否锁定",
                        align:"center",
                        // 0：锁定 1：未锁定
                        dataIndex:"status",
                        render(status, rows){
                            return (
                                <Switch checked={status===0} onChange={()=>{
                                        console.log(status, rows,'0表示锁定')
                                        // dispatch(getHospitalSetLockIdAsync(rows.id, status, form.getFieldsValue()))
                                    dispatch(changeQuery(form.getFieldsValue())); // 优化搜索及锁定
                                    dispatch(getHospitalSetLockIdAsync(rows.id, status))
                                }} />
                            )
                        }
                    },{
                        title:"api基础地址",
                        align:"center",
                        dataIndex:"apiUrl"
                    },{
                        title:"密钥",
                        align:"center",
                        width:150,
                        ellipsis:true,// 超过宽度将自动省略
                        dataIndex:"signKey"
                    },{
                        title:"联系人姓名",
                        align:"center",
                        dataIndex:"contactsName"
                    },{
                        title:"联系人手机",
                        align:"center",
                        dataIndex:"contactsPhone"
                    },{
                        title:"添加时间",
                        align:"center",
                        dataIndex:"createTime"
                    },{
                        title:"更新时间",
                        align:"center",
                        dataIndex:"updateTime"
                    },{
                        title:"操作",
                        align:"center",
                        // dataIndex:"hosname",
                        fixed:"right",// 右浮动
                        //render总共有3个参数，如果写了dataIndex，则第一个参数代表的是dataIndex的值，如果没写
                        //则第一个参数代表的是当前行的值，是一个对象，
                        //第二个参数是当前行的对象，第3个参数是数字序号，从0开始
                        /*
                        * render:生成复杂数据的渲染函数，参数分别为当前行的值，当前行数据，行索引
                        *
                        * */
                        render(rows){
                            // console.log(a, b, c, '0099099090')
                            return (
                                <Space>
                                    <Tooltip title="编辑">
                                        <Button onClick={() => {
                                            setHospitalSetInfo({...rows})
                                            setModalTitle('修改医院设置')
                                            setIsModalVisible(true)

                                        }} type="primary" shape="circle" icon={<FormOutlined />} />
                                    </Tooltip>
                                    <Popconfirm // 弹出删除确认框组件
                                        // visible={selectedId === rows.id} //判断id相同，就显示选框，否则不显示
                                        placement="topRight"
                                        title={"确认要删除"+rows.hosname+"的信息嘛"}
                                        onConfirm={
                                            //方式2
                                            () => {
                                                dispatch(delHospitalSetByIdAsync(rows.id)).then(
                                                    () => {
                                                        message.success('删除'+rows.hosname+'成功');
                                                    },
                                                    (err:any) => {
                                                        message.error(err.message);
                                                        // setSelectedId(-1);//让选框消失
                                                    }
                                                )
                                            }

                                            // 方式1  //只有当使用async的时候才需使用visible，来控制异步框的消失与显示
                                            // async () => { //当点击ok时才会执行
                                            //     // console.log('是');
                                            //    try {
                                            //        await dispatch(delHospitalSetByIdAsync(rows.id));
                                            //        setSelectedId(-1); //让选框消失
                                            //        message.success('删除成功');
                                            //    } catch (e) {
                                            //        // setSelectedId(-1);//让选框消失
                                            //        setTimeout(() => {
                                            //            setSelectedId(-1);//让选框2秒后消失
                                            //        },2000)
                                            //    }
                                            // }
                                        }
                                        onCancel = { //点击否的时候才会执行
                                            () => {
                                                // setSelectedId(-1);
                                            }
                                        }
                                        okText="是"
                                        cancelText="否"
                                    >
                                        <Tooltip title="删除">
                                            <Button onClick={() => {
                                                setSelectedId(rows.id);
                                            }} danger type="primary" shape="circle" icon={<DeleteOutlined />} />
                                        </Tooltip>
                                    </Popconfirm>

                                </Space>
                            )
                        }
                    }
                ]}
                dataSource={hospSetList}/>
            <HospitalModal hospitalSetInfo={hospitalSetInfo}
                           isModalVisible={isModalVisible}
                           modalTitle={modalTitle}
                           setIsModalVisible={setIsModalVisible}></HospitalModal>
        </div>
    );
}

export default HospitalSet;
